<template>
  <el-card>
    <el-button type="primary" @click="goCancelBook" style="margin-bottom: 20px"
      >取消预约</el-button
    >
    <el-row :gutter="10">
      <el-col :xs="24" :sm="24" :md="18" :lg="18" :xl="18">
        <el-card>
          <el-form v-model="queryParams" ref="queryParamsRef" :inline="true">
            <el-form-item :label="personReserved + '姓名'">
              <el-input
                :placeholder="'请输入' + personReserved + '姓名'"
                v-model="queryParams.nickName"
                size="small"
                clearable
              ></el-input>
            </el-form-item>
            <el-form-item label="日期">
              <el-date-picker
                v-model="queryParams.bookDate"
                align="right"
                type="date"
                clearable
                @input="changeTime"
                size="small"
                placeholder="选择搜索日期"
                :picker-options="pickerOptions"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="时间段">
              <el-time-picker
                v-model="timeFrame"
                is-range
                size="small"
                format="HH:mm"
                value-format="HH:mm"
                :style="{ width: '100%' }"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                range-separator="至"
                clearable
              >
              </el-time-picker>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                icon="el-icon-search"
                size="mini"
                @click="search"
                >搜索</el-button
              >
              <el-button
                icon="el-icon-refresh"
                size="mini"
                @click="resetSearchData"
                >重置</el-button
              >
            </el-form-item>
          </el-form>
          <el-table
            v-loading="loading"
            :data="slicesList"
            stripe
            border
            style="width: 480px; margin: 0 auto !important"
          >
            <el-table-column
              :label="personReserved"
              prop="nickName"
              width="80"
            />
            <el-table-column label="日期" prop="bookDate" width="100" />
            <el-table-column label="时间段范围" width="110">
              <template slot-scope="scope">
                {{ scope.row.startTime }}至{{ scope.row.endTime }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80" align="center">
              <template slot-scope="scope">
                <el-button size="mini" type="success" @click="book(scope.row)"
                  >预约</el-button
                >
              </template>
            </el-table-column>
            <el-table-column
              label="预约人数"
              prop="numBooked"
              width="110"
              align="center"
            >
              <template slot-scope="scope"
                >{{ scope.row.numBooked }}/{{ scope.row.numLimit }}</template
              >
            </el-table-column>
          </el-table>
          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="24" :md="6" :lg="6" :xl="6">
        <el-card>
          <el-table v-loading="noticeLoading" :data="noticeList">
            <el-table-column
              label="公告"
              align="left"
              prop="noticeTitle"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              label="创建者"
              align="center"
              prop="createBy"
              width="70"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              label="创建时间"
              align="center"
              prop="createTime"
              width="100"
              :show-overflow-tooltip="true"
            >
              <template slot-scope="scope">
                <span>{{
                  parseTime(scope.row.createTime, "{y}-{m}-{d}")
                }}</span>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="noticeTotal > 0"
            :total="noticeTotal"
            :page.sync="noticeQueryParams.pageNum"
            :limit.sync="noticeQueryParams.pageSize"
            @pagination="getNoticeList"
          />
        </el-card>
      </el-col>
    </el-row>
    <el-dialog title="预约" :visible.sync="open" width="95%">
      <el-form
        ref="bookDialog"
        :model="form"
        :rules="rules"
        label-width="110px"
      >
        <el-row :gutter="10">
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
            <el-form-item :label="forWho + '姓名'" prop="childName">
              <el-input
                v-model="form.childName"
                placeholder="请输入姓名"
                maxlength="30"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col
            :xs="24"
            :sm="24"
            :md="12"
            :lg="12"
            :xl="12"
            v-if="forWho == '孩子'"
          >
            <el-form-item :label="forWho + '月龄'" prop="monthAge">
              <el-input-number
                v-model="form.monthAge"
                :min="1"
                :max="999"
                label="描述文字"
              ></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
            <el-form-item :label="booker + '手机号码'" prop="phone">
              <el-input
                v-model="form.phone"
                placeholder="请输入手机号码"
                maxlength="11"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
            <el-form-item :label="booker + '邮箱'" prop="email">
              <el-input
                v-model="form.email"
                placeholder="请输入邮箱"
                maxlength="50"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="!token">
          <el-col :xs="24" :sm="24" :md="6" :lg="6" :xl="6">
            <el-form-item prop="code">
              <el-input
                v-model="form.code"
                auto-complete="off"
                placeholder="请输入图片中数字计算结果"
                clearable
                @keyup.enter.native="submitForm"
              >
                <svg-icon
                  slot="prefix"
                  icon-class="validCode"
                  class="el-input__icon input-icon"
                />
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="6" :lg="6" :xl="6">
            <el-form-item prop="codeImg">
              <div>
                <img
                  :src="form.codeUrl"
                  @click="getCode"
                  class="login-code-img"
                />
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="mini" @click="submitForm"
          >确 定</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetBookDialog"
          >重置</el-button
        >
        <el-button @click="open = false" size="mini">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="详情"
      :visible.sync="showMoreDialog"
      width="65%"
      append-to-body
    >
      <el-table :data="detail">
        <el-table-column label="是否提前提醒" align="center" prop="preRemind" />
        <el-table-column
          label="提前提醒时间(小时)"
          align="center"
          prop="preRemindTime"
        />
        <el-table-column
          label="提前提醒内容"
          align="center"
          prop="preRemindContent"
        />
        <el-table-column
          label="预约成功是否立即发送通知"
          align="center"
          prop="sendImmediate"
        />
        <el-table-column
          label="预约成功立即发送的内容"
          align="center"
          prop="sendImmediateContent"
        />
        <el-table-column label="其它说明" align="center" prop="remark" />
      </el-table>
    </el-dialog>
  </el-card>
</template>

<script>
import { mapGetters } from "vuex";
import { getCodeNoOff } from "@/api/login";
import { addBook, checkFull } from "@/api/parent/book";
import { Message } from "element-ui";
import { listNotice } from "@/api/system/notice";
import {
  listByDetails,
  listSlices,
  getSlices,
  delSlices,
  addSlices,
  updateSlices,
} from "@/api/doctor/slices";
import { getFree_time } from "@/api/doctor/free_time";
export default {
  dicts: ["sys_notice_status", "sys_notice_type"],
  name: "Index",
  data() {
    return {
      total: 100,
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 20,
      },
      noticeQueryParams: {
        pageNum: 1,
        pageSize: 10,
        noticeTitle: undefined,
        createBy: undefined,
        status: undefined,
      },
      detail: [],
      noticeTotal: 100,
      dateRange: [],
      morning: [],
      afternoon: [],
      form: {
        childName: "",
        monthAge: 36,
        email: "",
        phone: "",
        codeUrl: "",
        captchaOnOff: true,
        uuid: "",
      },
      rules: {
        childName: [
          { required: true, message: "姓名不能为空", trigger: "blur" },
        ],
        email: [
          { required: true, message: "邮箱不能为空", trigger: "blur" },
          {
            type: "email",
            message: "'请输入正确的邮箱地址",
            trigger: ["blur", "change"],
          },
        ],
        phone: [
          { required: true, message: "手机号不能为空", trigger: "blur" },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
      },
      showMoreDialog: false,
      personReserved: "医生",
      booker: "家长",
      forWho: "孩子",
      timeFrame: "",
      slicesList: [],
      noticeList: [],
      bookData: {},
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now();
        },
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              picker.$emit("pick", new Date());
            },
          },
          {
            text: "明天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() + 3600 * 1000 * 24);
              picker.$emit("pick", date);
            },
          },
          {
            text: "一周后",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() + 3600 * 1000 * 24 * 7);
              picker.$emit("pick", date);
            },
          },
        ],
      },
      addBookData: {},
    };
  },
  created() {
    this.getConfigKey("sys.personReserved").then((response) => {
      this.personReserved = response.msg;
    });
    this.getConfigKey("sys.title").then((response) => {
      document.title = response.msg;
    });
    this.getList();
    this.getNoticeList();
  },
  computed: {
    ...mapGetters(["token"]),
  },
  methods: {
    async resetBookDialog() {
      await this.resetForm("bookDialog");
      this.getCode();
    },
    changeTime() {
      console.log(this.timeFrame)
      this.$forceUpdate();
    },
    getNoticeList() {
      this.noticeLoading = true;
      listNotice(this.noticeQueryParams).then((response) => {
        this.noticeList = response.rows;
        this.noticeTotal = response.total;
        this.noticeLoading = false;
      });
    },
    search() {
      this.queryParams.pageNum = 1;
      this.queryParams.pageSize = 20;
      this.getList();
    },
    getList() {
      this.loading = true;
      if (this.queryParams.bookDate) {
        this.queryParams.bookDate = this.parseTime(
          this.queryParams.bookDate,
          "{y}-{m}-{d}"
        );
      } else {
        this.queryParams.bookDate = null;
      }
      if (this.timeFrame && this.timeFrame.length > 0) {
        this.queryParams.startTime = this.timeFrame[0];
        this.queryParams.endTime = this.timeFrame[1];
      } else {
        this.queryParams.startTime = null;
        this.queryParams.endTime = null;
      }
      listByDetails(this.queryParams).then((response) => {
        this.slicesList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    goCancelBook() {
      this.$router.push("/cancelBook");
    },
    showMore(freeTimeId) {
      getFree_time(freeTimeId).then((response) => {
        this.detail = [];
        this.detail.push(response.data);
        this.dateRange[0] = this.detail.dateRange1;
        this.dateRange[1] = this.detail.dateRange2;
        this.morning[0] = this.detail.morning1;
        this.morning[1] = this.detail.morning2;
        this.afternoon[0] = this.detail.afternoon1;
        this.afternoon[1] = this.detail.afternoon2;
        this.showMoreDialog = true;
      });
    },
    book(row) {
      var v = this;
      checkFull(row)
        .then((res) => {
          this.bookData = row;
          if (!this.token) {
            this.getCode();
          }
          this.getConfigKey("sys.booker").then((response) => {
            this.booker = response.msg;
          });
          this.getConfigKey("sys.forWho").then((response) => {
            this.forWho = response.msg;
          });
          this.open = true;
        })
        .catch(() => {
          v.getList();
        });
    },
    getCode() {
      getCodeNoOff().then((res) => {
        this.form.codeUrl = "data:image/gif;base64," + res.img;
        this.form.uuid = res.uuid;
      });
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleNoticeQuery();
    },
    resetSearchData() {
      this.queryParams.bookDate = "";
      this.queryParams.nickName = "";
      this.queryParams.pageNum = 1;
      this.queryParams.pageSize = 20;
      this.$set(this, "timeFrame", "");
      this.queryParams.startTime = "";
      this.queryParams.endTime = "";
      this.handleQuery();
    },

    submitForm() {
      this.$refs["bookDialog"].validate((valid) => {
        if (valid) {
          this.form.bookDate = this.bookData.bookDate;
          this.form.startTime = this.bookData.startTime;
          this.form.endTime = this.bookData.endTime;
          this.form.freeTimeId = this.bookData.freeTimeId;
          this.form.timeSliceId = this.bookData.id;
          this.form.userId = this.bookData.userId;
          this.form.userNickname = this.bookData.nickName;
          this.form.status = 0;
          addBook(this.form)
            .then((response) => {
              this.$message.success("预约成功");
              console.log("this", this);
              this.getList();
              this.open = false;
            })
            .catch(() => {
              if (!this.token) {
                this.getCode();
              }
            });
        } else {
          console.log("valid", valid);
        }
      });
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.queryParams.pageSize = 20;
      this.getList();
    },
    handleNoticeQuery() {
      this.noticeQueryParams.pageNum = 1;
      this.noticeQueryParams.pageSize = 10;
      this.getNoticeList();
    },
  },
};
</script>

<style scoped rel="stylesheet/scss" lang="scss">
.login-code {
  width: 33%;
  height: 38px;
  float: right;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}
.login-code-img {
  height: 38px;
}
</style>
